// pages/admin/role-permissions/role-permissions.js
const { authManager } = require('../../../utils/auth');

Page({
  data: {
    roles: [],
    loading: true,
    selectedRole: null,
    applications: [],
    showModal: false
  },

  onLoad() {
    // 检查管理员权限
    if (!authManager.pageAdminCheck()) {
      return;
    }
    this.loadRoles();
  },

  onShow() {
    // 检查管理员权限
    if (!authManager.pageAdminCheck()) {
      return;
    }
    this.loadRoles();
  },

  // 加载角色列表
  loadRoles() {
    this.setData({ loading: true });

    wx.request({
      url: `${getApp().globalData.serverUrl}/GetRolePermissions/`,
      method: 'POST',
      data: {
        admin_username: wx.getStorageSync('username')
      },
      success: (res) => {
        if (res.data.status) {
          console.log(res.data.roles) 
          // 预处理角色数据
          const roles = res.data.roles.map(role => ({
            ...role,
            displayName: this.getRoleDisplayName(role.id),
            permissionCount: role.permission_count || 0
          }));

          this.setData({
            roles: roles,
            loading: false
          });
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          });
          this.setData({ loading: false });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    });
  },

  // 获取角色显示名称
  getRoleDisplayName(roleId) {
    const roleNames = {
      1: '管理组', 2: '规划设计中心许可组', 3: '商务服务组',
      4: '数据勘测中心许可组', 5: '资源评价中心许可组',
      6: '评估咨询一中心许可组', 7: '评估咨询二中心许可组',
      8: '经纪代理中心许可组', 9: '江阴事业中心许可组',
      10: '南京事业中心许可组', 11: '普通用户', 12: '离职'
    };
    return roleNames[roleId] || `角色${roleId}`;
  },

  // 管理角色权限
  manageRolePermissions(e) {
    const roleId = parseInt(e.currentTarget.dataset.roleId);
    const role = this.data.roles.find(r => r.id === roleId);
    
    if (!role) return;

    this.setData({ selectedRole: role });
    this.loadRoleApplications(roleId);
  },

  // 加载角色的应用权限
  loadRoleApplications(roleId) {
    wx.showLoading({ title: '加载中...' });

    wx.request({
      url: `${getApp().globalData.serverUrl}/GetRoleApplications/`,
      method: 'POST',
      data: {
        admin_username: wx.getStorageSync('username'),
        role_id: roleId
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.status) {
          // 预处理应用数据
          const applications = res.data.applications.map(app => ({
            ...app,
            displayDescription: app.description || '暂无描述'
          }));

          this.setData({
            applications: applications,
            showModal: true
          });
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 切换应用权限
  toggleAppPermission(e) {
    const appId = parseInt(e.currentTarget.dataset.appId);
    const app = this.data.applications.find(item => item.id === appId);
    
    if (!app || !this.data.selectedRole) return;

    const action = app.has_permission ? 'revoke' : 'grant';
    const actionText = app.has_permission ? '撤销' : '授权';

    wx.showModal({
      title: '确认操作',
      content: `确定要${actionText}角色"${this.data.selectedRole.displayName}"对应用"${app.name}"的权限吗？`,
      success: (res) => {
        if (res.confirm) {
          this.performRolePermissionAction(appId, action);
        }
      }
    });
  },

  // 执行角色权限操作
  performRolePermissionAction(appId, action) {
    wx.showLoading({ title: '处理中...' });

    wx.request({
      url: `${getApp().globalData.serverUrl}/UpdateRolePermissions/`,
      method: 'POST',
      data: {
        admin_username: wx.getStorageSync('username'),
        role_id: this.data.selectedRole.id,
        permissions: [{ app_id: appId, action: action }]
      },
      success: (res) => {
        wx.hideLoading();
        if (res.data.status) {
          wx.showToast({
            title: '操作成功',
            icon: 'success'
          });
          // 重新加载角色应用权限
          this.loadRoleApplications(this.data.selectedRole.id);
          // 重新加载角色列表以更新权限计数
          this.loadRoles();
        } else {
          wx.showToast({
            title: res.data.message || '操作失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  },

  // 关闭模态框
  closeModal() {
    this.setData({ 
      showModal: false,
      selectedRole: null,
      applications: []
    });
  },

  // 阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡
  }
});